import { Injectable } from '@nestjs/common';
import { eq, sql } from 'drizzle-orm';
import { DrizzleService } from '../../db/drizzle.service';
import { users } from '../../db/schema';
import { CreateUserDto, UpdateUserDto, QueryUserDto } from './dto/user.schema';
import { EncryptionService } from '../../common/services/encryption.service';
import { PaginationService } from '../../common/services/pagination.service';
import { PaginationUtil } from '../../common/utils/pagination.util';

@Injectable()
export class UserService {
  constructor(
    private readonly drizzle: DrizzleService,
    private readonly encryptionService: EncryptionService,
    private readonly paginationService: PaginationService,
  ) { }

  async create(user: CreateUserDto) {
    // 如果提供了密码，则对其进行加密
    if (user.password) {
      user.password = await this.encryptionService.hashPassword(user.password);
    }

    return await this.drizzle.db.insert(users).values(user);
  }

  async findAll(query?: QueryUserDto) {
    // 标准化分页参数
    const pagination = PaginationUtil.normalizePagination(query);
    
    // 构建查询条件
    const conditions = [
      // 模糊查询
      ...PaginationUtil.buildLikeConditions(users, ['userName', 'nickName', 'phonenumber'], query),
      // 精确匹配
      ...PaginationUtil.buildEqualConditions(users, ['deptId'], query),
      // 枚举匹配
      ...PaginationUtil.buildEnumConditions(users, ['status'], query),
    ];

    // 构建排序
    const orderBy = PaginationUtil.buildOrderBy(users, undefined, 'asc');

    return await this.paginationService.paginate(
      users,
      pagination,
      {
        where: conditions,
        orderBy,
      }
    );
  }

  async findOne(id: number) {
    return await this.drizzle.db
      .select()
      .from(users)
      .where(eq(users.userId, id));
  }

  async update(id: number, user: UpdateUserDto) {
    // 如果提供了密码，则对其进行加密
    if (user.password) {
      user.password = await this.encryptionService.hashPassword(user.password);
    }

    return await this.drizzle.db
      .update(users)
      .set(user)
      .where(eq(users.userId, id));
  }

  async remove(id: number) {
    return await this.drizzle.db
      .delete(users)
      .where(eq(users.userId, id));
  }
}